package com.gombe.credit.app.ui.fragment

import android.annotation.SuppressLint
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonFragment
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.FragmentGombeCreditStepGeneralBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.ui.activity.ActGombeCreditProcessSteps
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditStepGeneral
import com.gombe.credit.app.ui.popupwindow.PopupwindowGombeCreditGeneral
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.decoration.LinearSpacingItemDecoration
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.weight.font.LexendSemiBoldButton
import com.gombe.credit.app.weight.pickerview.builder.TimePickerBuilder
import com.gombe.credit.app.weight.pickerview.listener.OnTimeSelectListener
import com.gombe.credit.app.weight.pickerview.view.TimePickerView
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 14:19
 * @Annotation：认证流程 - 通用
 */
class FragmentGombeCreditStepGeneral(): CommonFragment() {
    private var _binding: FragmentGombeCreditStepGeneralBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit step common binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepItem: JSONObject? = null
    private var eventRemark = ""

    private var generalAdapter: AdapterGombeCreditStepGeneral? = null
    private var mSelectPosition = -1

    //出生日期选择
    private var pvStartDateView: TimePickerView? = null
    var startTime = 0L

    constructor(data: JSONObject): this(){
        this.stepItem = data
        this.eventRemark = data.optString("stepTitle")
    }

    override fun takeGombeCreditRootView(inflater: LayoutInflater): View {
        _binding = FragmentGombeCreditStepGeneralBinding.inflate(inflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        setGombeCreditRootParentBackgroundColor(getColor(R.color.transparent))
        initAuthStepListView()

        //提交移到外层
        _binding?.authStepCommonNext?.visibility = View.INVISIBLE
        _binding?.textCreditLimitAddAmount?.visibility = View.INVISIBLE
    }

    override fun initGombeCreditListener() {
        //下一步
        _binding?.authStepCommonNext?.setOnClickListener {
            onGombeCreditStepGeneralSubmitAction()
        }
    }

    override fun takeGombeCreditData() {
        if (eventRemark == "personal_info"){
            val showKey = getString(R.string.gombe_credit_process_step_personal_info_data_security_key)
            val showText = String.format(getString(R.string.gombe_credit_process_step_personal_info_data_security),showKey)
            val startIndex = showText.indexOf(showKey)
            val dataSecuritySpannable = SpannableString(showText)
            dataSecuritySpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FF000FCC)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            //加粗
//            dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            _binding?.textPersonalInfoDataSecurity?.text = dataSecuritySpannable
            _binding?.dataSecurityLayout?.visibility = View.VISIBLE

            //个人信息额度增加数额 = 产品额度 / 2 * 0.05
            _binding?.textCreditLimitAddAmount?.text = String.format(getString(R.string.gombe_credit_process_step_loan_amount_add),"+${stepItem?.optString("creditLimitAmount")}")
            _binding?.textCreditLimitAddAmount?.visibility = View.INVISIBLE
        } else {
            _binding?.dataSecurityLayout?.visibility = View.GONE
            _binding?.textCreditLimitAddAmount?.visibility = View.GONE
        }

        val dataList = arrayListOf<JSONObject>()
        if (stepItem != null){
            addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_COMMON_XX_START,eventRemark),"")

            val dataArray = stepItem?.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
        }
        generalAdapter?.data = dataList
    }

    /**
     * 初始化Views
     */
    private fun initAuthStepListView(){
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.authStepCommonListView?.layoutManager = layoutManager
        val topDecoration = GombeCreditDensityUtil.dp2px(16f)
        _binding?.authStepCommonListView?.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        generalAdapter = AdapterGombeCreditStepGeneral(_binding?.authStepCommonListView)
        _binding?.authStepCommonListView?.adapter = generalAdapter
        _binding?.authStepCommonListView?.itemAnimator = DefaultItemAnimator()
        generalAdapter?.setOnItemChildClickListener { _, childView, position ->
            _binding?.root?.clearFocus()
            mSelectPosition = position
            generalAdapter?.let {
                val item = it.getItem(position)
                when (item.optString("action")) {
                    "DATE_PICK" -> {//时间选择
                        showGombeCreditStepBirthdayDialog()
                    }
                    "SELECT" -> {//选择
                        val dataList = arrayListOf<JSONObject>()
                        val dataArray = item.optJSONArray("values")
                        if (dataArray != null) {
                            for (i in 0..<dataArray.length()) {
                                dataList.add(dataArray.optJSONObject(i))
                            }
                        }
                        showSelectPopupwindow(childView, dataList)
                    }
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = PopupwindowGombeCreditGeneral(requireContext())
        selectPopup.setWindowWidth(view.width + GombeCreditDensityUtil.dp2px(10f))
        selectPopup.setSelectItemListener(object : PopupwindowGombeCreditGeneral.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                generalAdapter?.let {
                    val item = it.getItem(mSelectPosition)
                    item.put("selectItem",data)
                    it.notifyItemChanged(mSelectPosition)

                    if (data != null){
                        val subRemark = "${data.optString("value")}$$${data.optString("duration")}"
                        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_XX_SELECT,item.optString("paramName")),subRemark)
                    }
                }
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        _binding?.let {
            selectPopup.show(view, it.root)
            selectPopup.setBrandList(dataList)
        }
    }

    private fun showGombeCreditStepBirthdayDialog(){
        //开始选择时间
        startTime = System.currentTimeMillis()
        if(pvStartDateView == null){
            //时间可选范围18-100岁
            //当前日期
            val curtDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.timeInMillis = curtDate.timeInMillis
            startDate.add(Calendar.YEAR,-100)

            val endDate = Calendar.getInstance()
            endDate.timeInMillis = curtDate.timeInMillis
            endDate.add(Calendar.YEAR,-18)

            pvStartDateView = TimePickerBuilder(requireContext(), object : OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                }

                @SuppressLint("SimpleDateFormat")
                override fun onTimeSelectString(date: Date?, showDate: String?) {
                    val value = SimpleDateFormat("yyyy-MM-dd").format(date)
                    //可根据需要自行截取数据显示
                    val item = generalAdapter?.getItem(mSelectPosition)
                    item?.let {
                        val obj = JSONObject()
                        obj.put("title",showDate)
                        obj.put("title_sw",showDate)
                        obj.put("value",value)
                        it.put("selectItem",obj)

                        generalAdapter?.notifyItemChanged(mSelectPosition)

                        val subRemark = "${value}$$${System.currentTimeMillis() - startTime}"
                        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_XX_SELECT,item.optString("paramName")),subRemark)
                    }
                }
            })
                .setDate(endDate) //默认选中
                .setRangDate(startDate, endDate) //可选择时间范围
                .setLayoutRes(R.layout.dialog_gombe_credit_birthdate) { v ->
                    val ivClose = v.findViewById<ImageView>(R.id.imgClose)
                    ivClose.setOnClickListener {
                        pvStartDateView?.dismiss()
                    }
                    //确定
                    val btnConfirm = v.findViewById<LexendSemiBoldButton>(R.id.btnConfirm)
                    btnConfirm.setOnClickListener {
                        pvStartDateView?.returnData()
                        pvStartDateView?.dismiss()
                    }
                }
                .isDialog(true)
                .setContentTextSize(16)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3.5f)
                .setTextXOffset(65, 65, 65, 65, 65, 65)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter(getColor(R.color.gombe_credit_ff1d1e20)) //设置选中项文字颜色
                .setTextColorOut(getColor(R.color.gombe_credit_ffc8c8c8))//默认颜色
                .setBgColor(getColor(R.color.transparent))
                .isAlphaGradient(true)
                .setItemVisibleCount(3)
                .isCyclic(true)
                .setDividerColor(ContextCompat.getColor(requireContext(), R.color.transparent))
                .build()
            val dialog = pvStartDateView?.dialog
            dialog?.let {
                val dialogWindow = it.window
                if (dialogWindow != null) {
                    val params = dialogWindow.attributes
                    params.width = WindowManager.LayoutParams.MATCH_PARENT
                    params.height = WindowManager.LayoutParams.WRAP_CONTENT
                    dialogWindow.attributes = params
                    dialogWindow.setWindowAnimations(R.style.dialog_scale_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.CENTER)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView?.show()
    }

    /**
     * 提交信息
     */
    private fun onGombeCreditStepGeneralSubmitAction(){
        _binding?.root?.clearFocus()
        if (stepItem == null){
            return
        }
        if (!isAllowCommonSubmit()){
            showErrorTipsDialog(getString(R.string.gombe_credit_dialog_tips_submit_error), eventRemark)
            return
        }
        val params = JSONObject().addCommonParams()
        stepItem?.let {
            params.put("path",it.optString("apiUrl").replace("/",""))
        }
        generalAdapter?.let {
            for (i in 0..<it.itemCount){
                val item = it.getItem(i)
                if (item.has("selectItem")){
                    val selectItem = item.optJSONObject("selectItem")
                    if (selectItem != null){
                        params.put(item.optString("paramName"),selectItem.optString("value"))
                    }
                }
            }
        }
        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_XX_NEXT, eventRemark),"")
        // TODO: 进件信息点下一步 需上报所有埋点
        GombeCreditPointManager.getInstance().manualReport()

        GombeCreditLogger.e(">>>>>>submit data >>>>>>>$params")
        val act = getAct() as ActGombeCreditProcessSteps
        act.onGombeCreditProcessStepSubmitAction(params)
    }

    /**
     * 通用类型列表
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowCommonSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        generalAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                //存在 isMust && isMust == ”NO“  非必填
                if (item.has("isMust") && item.optString("isMust") == "NO"){
                    continue
                }
                //必填 && 没有内容 || 内容为空
                if (!item.has("selectItem")){
                    isAllow = false
                    break
                }
                val selectItem = item.optJSONObject("selectItem")
                if (selectItem == null){
                    isAllow = false
                    break
                }
                if (selectItem.optString("value").isEmpty()){
                    isAllow = false
                    break
                }
            }
        }
        return isAllow
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        when(event.eventType){
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_STEP_SUBMIT -> {
                onGombeCreditStepGeneralSubmitAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_COMMON_XX_END,eventRemark),"")
    }
}